//
//  Utils.m
//  moon
//
//  Created by beyself on 16/6/6.
//  Copyright © 2016年 beyself. All rights reserved.
//
#import <CommonCrypto/CommonDigest.h>
#import "AFHTTPSessionManager.h"
#import "Utils.h"
#import "BaseViewController.h"

@implementation Utils

+ (NSString *)ToHex:(uint16_t)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    uint16_t ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    return str;
}

+ (BOOL) isStringNullOrEmpty:(NSObject*)obj
{
    if(!obj) return YES;
    NSString* str = [obj description];
    if([str containsString:@"null"] || !str.length) return YES;
    return NO;
}

+ (void) saveDefaultUser:(NSString*)obj key:(NSString*)key
{
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    [accountDefaults setObject:obj forKey:key];
}

+ (NSString*) readDefaultUser:(NSString*)key
{
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    return [accountDefaults objectForKey:key];
}

+ (void) saveCustomObject:(NSObject *)obj key:(NSString*)key
{
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:myEncodedObject forKey:key];
}

+ (NSObject *)loadCustomObjectWithKey:(NSString *)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [defaults objectForKey:key];
    NSObject *obj = (NSObject *)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
    return obj;
}

+ (UIImage *) imageFromColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext(); return img;
}

+ (NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char result[32];
    
    CC_MD5( cStr, strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0],result[1],result[2],result[3],
            result[4],result[5],result[6],result[7],
            result[8],result[9],result[10],result[11],
            result[12],result[13],result[14],result[15],
            result[16], result[17],result[18], result[19],
            result[20], result[21],result[22], result[23],
            result[24], result[25],result[26], result[27],
            result[28], result[29],result[30], result[31]];
}

+ (void) sendHttpPostNOWait:(NSMutableDictionary*)param method:(NSString*)method controller:(BaseViewController*)controller flag:(int)flag
{
    [param setValue:[self md5:[NSString stringWithFormat:@"%@ylbb",method]] forKey:@"sec"];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:[NSString stringWithFormat:@"http://120.27.129.233/ylbb/api/%@",method]
       parameters:param constructingBodyWithBlock:^(id  _Nonnull formData) {
           // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
           
       } progress:^(NSProgress * _Nonnull uploadProgress) {
           // 这里可以获取到目前的数据请求的进度
           
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
           if([NSStringFromClass(dic.class) containsString:@"NSArray"] || [dic[@"statusCode"] intValue] == 0)
           {
               [controller httpCallback:dic flag:flag];
           }
           else
           {
               [controller showMsg:dic[@"message"]];
           }
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [controller showAllTextDialog:@"网络状况不佳，请稍后重试..."];
           @try {
               [controller httpCallbackFail:flag];
           } @catch (NSException *exception) {
               
           } @finally {
               
           }
       }];
}

+ (void) sendHttpLogin
{
    NSString* username = [Utils readDefaultUser:@"username"];
    if(!username || !username.length) return;
    
    NSString* method = @"member_login";
    
    NSMutableDictionary* param = [[NSMutableDictionary alloc] init];
    [param setObject:[Utils readDefaultUser:@"username"] forKey:@"phonenumber"];
    [param setObject:[Utils readDefaultUser:@"password"] forKey:@"password"];
    if(APPDELEGATE.deviceToken.length) [param setObject:APPDELEGATE.deviceToken forKey:@"ios_token"];
    [param setValue:[self md5:[NSString stringWithFormat:@"%@ylbb",method]] forKey:@"sec"];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager POST:[NSString stringWithFormat:@"http://120.27.129.233/ylbb/api/%@",method]
       parameters:param constructingBodyWithBlock:^(id  _Nonnull formData) {
       } progress:^(NSProgress * _Nonnull uploadProgress) {
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
           if([dic[@"statusCode"] intValue] == 0)
           {
               [Utils saveCustomObject:dic[@"member"] key:LOGIN_INFO];
               [APPDELEGATE.mMemberInfo setDictionary:dic[@"member"]];
           }
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       }];
}

+ (void) sendHttpPost:(NSMutableDictionary*)param method:(NSString*)method controller:(BaseViewController*)controller flag:(int)flag
{
    [controller showWaitDialog];
    [param setValue:[self md5:[NSString stringWithFormat:@"%@ylbb",method]] forKey:@"sec"];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:[NSString stringWithFormat:@"http://120.27.129.233/ylbb/api/%@",method]
       parameters:param constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [controller dissmissDialog];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        if([dic[@"statusCode"] intValue] == 0)
        {
            [controller httpCallback:dic flag:flag];
        }
        else
        {
            [controller showMsg:dic[@"message"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [controller dissmissDialog];
        [controller showAllTextDialog:@"网络状况不佳，请稍后重试..."];
        @try {
            [controller httpCallbackFail:flag];
        } @catch (NSException *exception) {
            
        } @finally {
            
        }
    }];
}

+ (void) sendHttpGet:(NSMutableDictionary*)param method:(NSString*)method controller:(UIViewController*)controller
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"20131129", @"date", @"1", @"startRecord", @"5", @"len", @"1234567890", @"udid", @"Iphone", @"terminalType", @"213", @"cid", nil];
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager GET:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前的数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功，解析数据
        NSLog(@"%@", responseObject);
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        NSLog(@"%@", dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    double width = image.size.width;
    double height = image.size.height;
    
    double widthRate = width/newSize.width;
    double heightRate = height/newSize.height;
    
    if(widthRate >= heightRate && widthRate > 1)
    {
        newSize.height = height/widthRate;
    }
    else if(heightRate > widthRate && heightRate > 1)
    {
        newSize.width = width/heightRate;
    }
    else
    {
        return image;
    }
    
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

+(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (NSString*) date2String:(NSDate*) date format:(NSString*)format
{
    NSDateFormatter *outputFormatter= [[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:format];
    return [outputFormatter stringFromDate:date];
}

+ (NSDate*) string2Date:(NSString*) date format:(NSString*)format
{
    NSDateFormatter *outputFormatter= [[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:format];
    return [outputFormatter dateFromString:date];
}

+ (NSString*) date2format:(NSString*)date
{
    if(date == nil || date.length == 0) return 0;
    
    NSDate* now = [NSDate date];
    NSDate* com = [self string2Date:date format:@"yyyy-MM-dd HH:mm:ss"];
    
    if([[self date2String:now format:@"yyyy-MM-dd"] isEqualToString:[self date2String:com format:@"yyyy-MM-dd"]])
    {
        return [NSString stringWithFormat:@"今天 %@",[self date2String:com format:@"HH:mm"]];
    }
    else if([now timeIntervalSince1970] - [com timeIntervalSince1970] < 24*3600)
    {
        return [NSString stringWithFormat:@"昨天 %@",[self date2String:com format:@"HH:mm"]];
    }
    else if([now timeIntervalSince1970] - [com timeIntervalSince1970] < 24*3600*30)
    {
        int day = ([now timeIntervalSince1970] - [com timeIntervalSince1970])/(24*3600);
        return [NSString stringWithFormat:@"%d天前",day];
    }
    else if([now timeIntervalSince1970] - [com timeIntervalSince1970] < 24*3600*30*12)
    {
        int day = ([now timeIntervalSince1970] - [com timeIntervalSince1970])/(24*3600*30);
        return [NSString stringWithFormat:@"%d月前",day];
    }
    
    return @"一年前";
}

@end
